###############################################################################
# InstantMessage.pl                                                           #
###############################################################################
# YaBB: Yet another Bulletin Board                                            #
# Open-Source Community Software for Webmasters                               #
# Version:        YaBB 2.2                                                    #
# Packaged:       November 8, 2007                                            #
# Distributed by: http://www.yabbforum.com                                    #
# =========================================================================== #
# Copyright (c) 2000-2007 YaBB (www.yabbforum.com) - All Rights Reserved.     #
# Software by:  The YaBB Development Team                                     #
#               with assistance from the YaBB community.                      #
# Sponsored by: Xnull Internet Media, Inc. - http://www.ximinc.com            #
#               Your source for web hosting, web design, and domains.         #
###############################################################################

$instantmessageplver = 'YaBB 2.2 $Revision: 1.106 $';
if ($action eq 'detailedversion') { return 1; }

## create the send IM section of the screen

####
# new format:  for  msg file:
#messageid|(from)user|(touser(s))|(ccuser(s))|(bccuser(s))|
#		subject|date|message|(parentmid)|reply#|ip|messagestatus|
##            flags|storefolder|attachment

# (optional) [placeholder]


# for outbox:
#messageid|(from)user|(touser(s))|(ccuser(s))|(bccuser(s))|
#		subject|date|message|(parentmid)|reply#|ip|messagestatus|
##            flags|storefolder|attachment

## messagestatus = c(onfidential)/h(igh importance)/s(tandard)/a(lert)/g(uest)/(b)roadcast/(n)otify of post
## flags = u(nread)/f(orward)/q(oute)/r(eply)
## parentmid stays same, reply# increments for replies, so we can build conversation threads
## storefolder = name of storage folder. Start with in & out for everyone. 
##
####
#1	$mnum = 3;
#2	$imnewcount = 0;
#3	$moutnum = 17;
#4	$storenum = 0;
#5	$draftnum = 0;
#6	@folders  (name1|name2|name3)

# MF-B: new .ims file format
#	### UserIMS YaBB 2.2 Version ###
#	'${$username}{'PMmnum'}',"value"
#	'${$username}{'PMimnewcount'}',"value"
#	'${$username}{'PMmoutnum'}',"value"
#	'${$username}{'PMstorenum'}',"value"
#	'${$username}{'PMdraftnum'}',"value"
#	'${$username}{'PMfolders'}',"value"
#	'${$username}{'PMfoldersCount'}',"value"

#	@storecurrentin = qw/ /; # list of messages in .imstore from msg
#	@storecurrentout = qw/ /; # list of messages in .imstore from outbox



sub buildIMsend	{

	&LoadLanguage('InstantMessage');
	&LoadLanguage('Post');
	&LoadCensorList;

	require "$sourcedir/Palette.pl";
	if ($FORM{'previewim'})	{
		require "$sourcedir/Post.pl";
		if (!$error){ &Preview; $subject = $csubject; }
		else	{ &Preview($error); }
	}
	$yyimbox = $inmes_txt{'775'};
	## check for a draft being opened
	if ($INFO{'caller'} == 4 && $INFO{'id'}) {
		if (!-e "$memberdir/$username.imdraft")	 { &fatal_error('cannot_open_file', "$username.imdraft");}
		fopen(DRAFT, "$memberdir/$username.imdraft");
		my @draftPM = <DRAFT>;
		fclose(DRAFT);
		chomp @draftPM;
		my $flagfound;
		foreach my $draftMess (@draftPM) {
			my ($checkId, undef) = split(/\|/, $draftMess, 2);
			if ($checkId eq $INFO{'id'}){
				($dmessageid, $dmusername, $userto, $usernamecc, $usernamebcc, $subject, $dmdate, $message, $dmpmessageid, $dmreplyno, $dmips, $dmessageStatus, $dmessageFlags, $dstoreFolder, $dmessageAttachment) = split(/\|/, $draftMess);
				$flagfound = 1;
				last;
			}	
		}
		if (!$flagfound) { &fatal_error('cannot_find_mess', "draft message cannot be found"); }
	}

	my $pmicon = 'standard';
	$stselect = '';
	$urselect = '';
	$cnselect = '';
	if ($FORM{'status'} || $INFO{'status'}) { $thestatus = $FORM{'status'} || $INFO{'status'}; }
	elsif ($dmessageStatus){ $thestatus = $dmessageStatus; }
	else { $thestatus = 's'; }

	if ($thestatus eq 's') { $stselect = qq~ selected="selected"~; }
	elsif ($thestatus eq 'u') { $urselect = qq~ selected="selected"~; }
	elsif ($thestatus eq 'c') { $cnselect = qq~ selected="selected"~; }

	##########   post code   ######################################
	if (!$iamadmin && !$iamgmod && !$staff && ${$uid.$username}{'postcount'} < $numposts) {
		&fatal_error('im_low_postcount');
	}

	if (!$replyguest) {
		my ($filetype_info, $filesize_info, $extensions);
		$extensions = join(" ", @ext);
		$filetype_info = $checkext == 1 ? qq~$fatxt{'2'} $extensions~ : qq~$fatxt{'2'} $fatxt{'4'}~;
		$filesize_info = $limit != 0 ? qq~$fatxt{'3'} $limit KB~ : qq~$fatxt{'3'} $fatxt{'5'}~;
		if ($is_preview) { $post_txt{'507'} = $post_txt{'771'}; }
		$normalquot = $post_txt{'599'};
		$simpelquot = $post_txt{'601'};
		$simpelcode = $post_txt{'602'};
		$edittext = $post_txt{'603'};
		if (!$fontsizemax) { $fontsizemax = 72; }
		if (!$fontsizemin) { $fontsizemin = 6; }
		
		$message =~ s~<\/~\&lt\;/~isg;
		if ($msubject) { $subject = $msubject; }
		$message = &Censor($message);
		$subject = &Censor($subject);
		&ToChars($message);
		&ToChars($subject);
		&FromHTML($message);
		&FromHTML($subject);
		$message =~ s~<br \/>~\n~ig;
		$message =~ s~<br>~\n~ig;
		$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;
		# this defines what the top area of the post box will look like: 
		## cloak the rec 
		my $toshow;
		## if this is a reply , load the 'from' name off the message
		if ($INFO{'reply'} || $INFO{'quote'}) { $INFO{'to'} = $mfrom; }
		if (!$INFO{'to'} && $FORM{'to'} ne '') { $INFO{'to'} = $FORM{'to'}; }

		## if cloaking is enabled, and 'to' is not a blank
		if ($do_scramble_id && $INFO{'to'} ne '') {
		 	&decloak($INFO{'to'});
		}

		if (!$sendBMess)	{
			$toshow = $INFO{'to'};
			&LoadUser($toshow);
		}

	} else {
		
		$message =~ s~<\/~\&lt\;/~isg;
		if ($msubject) { $subject = $msubject; }
		&ToChars($message);
		&ToChars($subject);
		&FromHTML($message);
		&FromHTML($subject);
		$message =~ s~<br \/>~\n~ig;
		$message =~ s~<br>~\n~ig;
		$message =~ s/ \&nbsp; \&nbsp; \&nbsp;/\t/ig;

	}

	$idinfo = $INFO{'id'};
	$imsend .= qq~
	<script language="JavaScript1.2" src="$yabbcjspath" type="text/javascript"></script>
	<script language="JavaScript1.2" src="$postjspath" type="text/javascript"></script>
	<script language="JavaScript1.2" src="$ubbcjspath" type="text/javascript"></script>
	<form action="$scripturl?$thecurboard" method="post" name="postmodify" id="postmodify" enctype="application/x-www-form-urlencoded" onsubmit="if(!checkForm(this)) {return false} else {return submitproc()}\;">
	~;

	if (((!$enable_PMcontrols && $enable_PMActprev) || $enable_PMcontrols && ${$uid.$username}{'pmactprev'} eq 'on') && !$replyguest) {
		$imsend .= qq~
	<tr>
		<td class="windowbg2" valign="top">
		<div id="SaveInfo" style="height: 16px;">
			<img src="$imagesdir/cat_expand.gif" name="prevwin" id="prevwin" alt="$npf_txt{'01'}" border="0" style="cursor: pointer;" onclick="enabPrev();" /> <b>$npf_txt{'04'}</b>
		</div>
		</td>
	</tr>
	<tr>
		<td class="windowbg2">
		<div id="savetopic" style="position: relative; top: 0px; left:0px; height: 0px; font-weight: bold; visibility: hidden; overflow: auto;">&nbsp;</div>
		<div id="saveframe" class="message" style="position: relative; top: 0px; left:0px; height: 0px; border-top: 1px black solid; padding-top: 4px; vertical-align: top; visibility: hidden; overflow: auto;">&nbsp;</div>
		</td>
	</tr>
		~;
	}
	
	if ($replyguest) {
		$imsend .= qq~
	<tr>
		<td class="windowbg2">
		$guest_reply{'guesttext'}
		</td>
	</tr>
		~;
	}

	if ($prevmain && !$replyguest) {
		$imsend .= qq~	 
	<tr>
		<td class="windowbg2">
		$prevmain
		</td>
	</tr>
	~;
	}

	$imsend .= qq~
	<tr>
		<td class="windowbg" width="50%">
			<table width="95%" align="left" cellpadding="2">
	~;	

if (!$replyguest && !$sendBMess && ($PMenable_cc || $PMenable_bcc)) {
	$yyjavascripttoform = qq~
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		function changeRecepientTab(tabto) {
			document.getElementById('usersto').style.display = 'none';
			document.getElementById('bnttoto').className = 'windowbg';
	~;
	$imsend .= qq~
			<tr>
				<td colspan="2" align="left">
				<div id="bnttoto" style="float: left; padding: 5px;" class="windowbg2"><a href="javascript:void(0);" onclick="changeRecepientTab('to'); return false;">$inmes_txt{'324'}:</a></div>
	~;	
	if ($PMenable_cc) {
		$yyjavascripttoform .= qq~
			document.getElementById('userscc').style.display = 'none';
			document.getElementById('bnttocc').className = 'windowbg';
		~;
		$imsend .= qq~
				<div id="bnttocc" style="float: left; padding: 5px;" class="windowbg"><a href="javascript:void(0);" onclick="changeRecepientTab('cc'); return false;">$inmes_txt{'325'}:</a></div>
		~;	
	}
	if ($PMenable_bcc) {
		$yyjavascripttoform .= qq~
			document.getElementById('usersbcc').style.display = 'none';
			document.getElementById('bnttobcc').className = 'windowbg';
		~;
		$imsend .= qq~
				<div id="bnttobcc" style="float: left; padding: 5px;" class="windowbg"><a href="javascript:void(0);" onclick="changeRecepientTab('bcc'); return false;">$inmes_txt{'326'}:</a></div>
		~;	
	}
	$yyjavascripttoform .= qq~
			document.getElementById('users' + tabto).style.display = 'inline';
			document.getElementById('bntto' + tabto).className = 'windowbg2';
		}
	//-->
	</script>
	~;
	$imsend .= qq~
					$yyjavascripttoform
				</td>
			</tr>
	~;	
}

	$imsend .= qq~
			<tr>
				<td width="50%" valign="top" align="left">
	~;	

	# now uses a multi-line select 
	&ProcIMrecs;
	$toname = '';
	$toshow = '';

	unless ($INFO{'forward'}) { $toname = $INFO{'to'}; }

	my $toUsersTitle = qq~$inmes_txt{'torecepients'}:~;
	
if (!$replyguest) {
	if ($sendBMess) { $toUsersTitle = qq~$inmes_txt{'togroups'}:~; }
	if ($PMenable_cc || $PMenable_bcc) {
		$us_winhight = 370;
	} else {
		$us_winhight = 345;
	}
	my $toIdtext = 'toshow';
	my $toIdtext2 = 'toshow';
	my $toIdtext3 = 'toshowcc';
	my $toIdtext4 = 'toshowpmbcc';
	if ($sendBMess) { $toIdtext = 'groups'; }

	$imsend  .= qq~
	<script language="JavaScript1.2" type="text/javascript">
    <!--
	function imWin() {
		window.open('$scripturl?action=imlist;sort=recentpm;toid=$toIdtext','','status=no,height=$us_winhight,width=464,menubar=no,toolbar=no,top=50,left=50,scrollbars=no');
	}
	function imWinCC() {
		window.open('$scripturl?action=imlist;sort=recentpm;toid=toshowcc','','status=no,height=$us_winhight,width=464,menubar=no,toolbar=no,top=50,left=50,scrollbars=no');
	}
	function imWinBCC() {
		window.open('$scripturl?action=imlist;sort=recentpm;toid=toshowbcc','','status=no,height=$us_winhight,width=464,menubar=no,toolbar=no,top=50,left=50,scrollbars=no');
	}
	function removeUser(oElement) {
		var indexToRemove = oElement.options.selectedIndex;
		if (confirm("$post_txt{'768'}")) { oElement.remove(indexToRemove); }
	}
	//-->
	</script>
	<div id="usersto" style="width: 98%; display: inline; float: left;">
	<b>$toUsersTitle</b>&nbsp;<a href="javascript: void(0);" onclick="imWin();"><span class="small">$inmes_txt{'clickto'}</span></a><br />
	<select name="toshow" id="toshow" multiple="multiple" size="6" style="width: 100%;" ondblclick="javascript: removeUser(this);">
	<optgroup class="titlebg" label="$inmes_txt{'324'}:" disabled="disabled"></optgroup> 
	~;

	my $usefields;
	if (!$sendBMess)	{
		if ($toname) {
			&LoadUser($toname);
			if(${$uid.$toname}{'realname'})	{
				$imsend  .= qq~<option selected="selected" value="$useraccount{$toname}">${$uid.$toname}{'realname'}</option>~;
			}
		}
		if ($FORM{'toshow'}) {
			foreach my $touser (split(/\,/, $FORM{'toshow'}))	{
				&LoadUser($touser);
				$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;	
			}
		}
		if ($userto) {
			foreach my $touser (split(/\,/, $userto))	{
				&LoadUser($touser);
				$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;	
			}
		}
	} else {

		if ($FORM{'toshow'})	{
			require "$vardir/membergroups.txt";
			foreach my $touser (split(/\,/, $FORM{'toshow'})) {
				if ($touser eq 'bmallmembers') { $imsend .= qq~<option selected="selected" value="bmallmembers">$inmes_txt{'bmallmembers'}</option>\n~; }
				elsif ($touser eq 'bmgmods') { $imsend .= qq~<option selected="selected" value="bmgmods">$inmes_txt{'bmgmods'}</option>\n~; }
				elsif ($touser eq 'bmmods') { $imsend .= qq~<option selected="selected" value="bmmods">$inmes_txt{'bmmods'}</option>\n~; }
				else {
					foreach (keys %NoPost) {
						my ($title, undef) = split(/\|/, $NoPost{$_}, 2);
						if ($touser eq $_) { $imsend .= qq~<option selected="selected" value="$_">$title</option>\n~; }
					}
				}
			}
		}

	}

	$imsend  .= qq~
		</select><input type="hidden" name="immulti" value="yes" />
		</div>
	~;
	
	$yyjavascriptimsend = qq~
	<script language="JavaScript1.2" type="text/javascript">
	<!--
	// this function forces all users listed on IM mult to be selected for processing
	function selectNames() {
		var oList = document.getElementById('toshow')
		for (var i = 0; i < oList.options.length; i++){ 	oList.options[i].selected = true;	}
	~;

	if (!$sendBMess)	{
		if ($PMenable_cc) {
			$yyjavascriptimsend  .= qq~
				var oList = document.getElementById('toshowcc') 
				for (var i = 0; i < oList.options.length; i++){ oList.options[i].selected = true; }
			~;
			$imsend .= qq~
			<div id="userscc" style="width: 98%; display: none; float: left;">
			<b>$toUsersTitle</b>&nbsp;<a href="javascript: void(0);" onclick="imWinCC();"><span class="small">$inmes_txt{'clickto'}</span></a><br />
			<select name="toshowcc" id="toshowcc" multiple="multiple" size="6" style="width: 100%;" ondblclick="javascript: removeUser(this);">
			<optgroup class="titlebg" label="$inmes_txt{'325'}:" disabled="disabled"></optgroup>
			~;
			if ($FORM{'toshowcc'}) {
				foreach my $touser (split(/\,/, $FORM{'toshowcc'})) {
					&LoadUser($touser);
					$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;
				}
			}
			if ($usernamecc)	{
				foreach my $touser (split(/\,/, $usernamecc)) {
					&LoadUser($touser);
					$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;
				}
			}
			$imsend .= qq~
			</select>
			</div>
			~;
		}

		if ($PMenable_bcc) {
			$yyjavascriptimsend  .= qq~
				var oList = document.getElementById('toshowbcc')
				for (var i = 0; i < oList.options.length; i++){ oList.options[i].selected = true; }
			~;
			$imsend .= qq~
			<div id="usersbcc" style="width: 98%; display: none; float: left;">
			<b>$toUsersTitle</b>&nbsp;<a href="javascript: void(0);" onclick="imWinBCC();"><span class="small">$inmes_txt{'clickto'}</span></a><br />
			<select name="toshowbcc" id="toshowbcc" multiple="multiple" size="6" style="width: 100%;" ondblclick="javascript: removeUser(this);">
			<optgroup class="titlebg" label="$inmes_txt{'326'}:" disabled="disabled"></optgroup>
   			~;
			if ($FORM{'toshowbcc'}) {
				foreach my $touser (split(/\,/, $FORM{'toshowbcc'})) {
					&LoadUser($touser);
					$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;	
				}
			}
			if ($usernamebcc) {
				foreach my $touser (split(/\,/, $usernamebcc)) {
					&LoadUser($touser);
					$imsend .= qq~<option selected="selected" value="$useraccount{$touser}">${$uid.$touser}{'realname'}</option>~;	
				}
			}
			$imsend .= qq~
			</select> 
			</div>
			~;
		}
	}

	$yyjavascriptimsend  .= qq~
		}
	//-->
	</script>
	~;

	$imsend  .= qq~
 				</td>
				<td width="50%" valign="top" align="left">
					<b>$inmes_txt{'status'}:</b><br />
					<select name="status" tabindex="2" size="3" onchange="showtpstatus();$onchangeText2">
					<option value="s"$stselect>$im_message_status{'standard'}</option>
					<option value="c"$cnselect>$im_message_status{'confidential'}</option>
					<option value="u"$urselect>$im_message_status{'urgent'}</option>
					</select><img src="$imagesdir/$pmicon.gif" name="icons" border="0" hspace="10" alt="$im_message_status{'$pmicon'}" />
				</td>
				</tr>
			</table>
		</td> 
	</tr>
	~;

} else {

	$imsend .= qq~
	<tr>
		<td class="windowbg">
		<b>$toUsersTitle:</b> <input type="text" name="toguest" id="toguest" value="$guestName" size="50" maxlength="25" style="width: 95%;"><input type="hidden" name="toshow" id="toshow" value="$guestName">
		</td> 
	</tr>
	<tr>
		<td class="windowbg">
		<b>$post_txt{'69'}:</b> <input type="text" name="guestemail" id="guestemail" value="$guestEmail" size="50" maxlength="40" style="width: 95%;">
		<input type="hidden" name="replyguest" id="replyguest" value="1" />
		</td> 
	</tr>
	~;

}

	$subtitle = "<i>$subject</i>";
	#this is the end of the upper area of the post page.

	# this declares the beginning of the UBBC section
	$imsend .= qq~
	<!--<div class="bordercolor" style="padding: 1px; width: 100%; margin-left: auto; margin-right: auto;"> AK108: XHTML validation -->
	$yyjavascriptimsend
	<script language="JavaScript1.2" type="text/javascript">
	<!--
	function showimage() {
		document.images.status.src=document.postmodify.status.options[document.postmodify.images.status.selectedIndex].value;
	}
	//-->
	</script>
	~;

	$imsend .= qq~
	    <input type="hidden" name="threadid" id="threadid" value="$threadid" />
	    <input type="hidden" name="postid" id="postid" value="$postid" />
	    <input type="hidden" name="info" id="info" value="$idinfo" />
	    <input type="hidden" name="mename" id="mename" value="$mename" />
	    <input type="hidden" name="post_entry_time" id="post_entry_time" value="$date" />
	~;

	if ($FORM{'draft'} || $INFO{'caller'} == 4) {
		$imsend .= qq~<input type="hidden" name="draftid" id="draftid" value="$INFO{'id'}" />~;
	}
	if ($INFO{'quote'}) {
		$imsend .= qq~<input type="hidden" name="quote" id="quote" value="1" />~;
	}
	if ($INFO{'reply'}) {
		$imsend .= qq~<input type="hidden" name="reply" id="reply" value="1" />~;
	}
	if ($INFO{'forward'}) {
		$imsend .= qq~<input type="hidden" name="forward" id="forward" value="1" />~;
	}

	my ($onchangeText, $onchangeText2);
	if (((!$enable_PMcontrols && $enable_PMActprev) || ${$uid.$username}{'pmactprev'} eq 'on') && !$replyguest) {
		$onchangeText = qq~ onchange="updatTopic();"~;
		$onchangeText2 = qq~ updatTopic();"~;
	}

	$imsend .= qq~
	<tr>
		<td align="left" class="windowbg2">
			<b>$inmes_txt{'70'}:</b> <input type="text" name="subject" value="$subject" size="50" maxlength="$set_subjectMaxLength" tabindex="1" style="width: 95%;"$onchangeText /> 
		</td>
	</tr>
	<tr>
		<td class="windowbg2">
	~;

	# this is for the ubbc buttons
	if (!$replyguest) {
		if ($enable_ubbc && $showyabbcbutt) {

			require "$sourcedir/Palette.pl";
			$ubbcpalette .= &Palette("post");

			$imsend .= qq~<b>$post_txt{'252'}:</b>
			<div style="float: left; width: 440px;">
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "WebTV Plus Receiver" && navigator.appVersion.charAt(0) >= 3) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer;'";
				document.write('<div style="width: 437px; float: left;">');
				document.write("<img src='$imagesdir/url.gif' onclick='hyperlink();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'257'}' title='$post_txt{'257'}' border='0' \/>");
				document.write("<img src='$imagesdir/ftp.gif' onclick='ftp();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'434'}' title='$post_txt{'434'}' border='0' \/>");
				document.write("<img src='$imagesdir/img.gif' onclick='image();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'435'}' title='$post_txt{'435'}' border='0' \/>");
				document.write("<img src='$imagesdir/email2.gif' onclick='emai1();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'258'}' title='$post_txt{'258'}' border='0' \/>");
				document.write("<img src='$imagesdir/media.gif' onclick='flash();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'433'}' title='$post_txt{'433'}' border='0' \/>");
				document.write("<img src='$imagesdir/table.gif' onclick='table();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'436'}' title='$post_txt{'436'}' border='0' \/>");
				document.write("<img src='$imagesdir/tr.gif' onclick='trow();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'449'}' title='$post_txt{'449'}' border='0' \/>");
				document.write("<img src='$imagesdir/td.gif' onclick='tcol();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'437'}' title='$post_txt{'437'}' border='0' \/>");
				document.write("<img src='$imagesdir/hr.gif' onclick='hr();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'531'}' title='$post_txt{'531'}' border='0' \/>");
				document.write("<img src='$imagesdir/tele.gif' onclick='teletype();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'440'}' title='$post_txt{'440'}' border='0' \/>");
				document.write("<img src='$imagesdir/code.gif' onclick='showcode();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'259'}' title='$post_txt{'259'}' border='0' \/>");
				document.write("<img src='$imagesdir/quote2.gif' onclick='quote();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'260'}' title='$post_txt{'260'}' border='0' \/>");
				document.write("<img src='$imagesdir/edit.gif' onclick='edit();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'603'}' title='$post_txt{'603'}' border='0' \/>");
				document.write("<img src='$imagesdir/sup.gif' onclick='superscript();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'447'}' title='$post_txt{'447'}' border='0' \/>");
				document.write("<img src='$imagesdir/sub.gif' onclick='subscript();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'448'}' title='$post_txt{'448'}' border='0' \/>");
				document.write("<img src='$imagesdir/list.gif' onclick='list();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'261'}' title='$post_txt{'261'}' border='0' />");
				document.write("<img src='$imagesdir/me.gif' onclick='me();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'604'}' title='$post_txt{'604'}' border='0' />");
				document.write("<img src='$imagesdir/move.gif' onclick='move();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'439'}' title='$post_txt{'439'}' border='0' \/>");
				document.write("<img src='$imagesdir/timestamp.gif' onclick='timestamp($date);' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'245'}' title='$post_txt{'245'}' border='0' \/><br />");
				document.write('</div>');
				document.write('<div style="width: 115px; float: left;">');
				document.write("<img src='$imagesdir/bold.gif' onclick='bold();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'253'}' title='$post_txt{'253'}' border='0' \/>");
				document.write("<img src='$imagesdir/italicize.gif' onclick='italicize();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'254'}' title='$post_txt{'254'}' border='0' \/>");
				document.write("<img src='$imagesdir/underline.gif' onclick='underline();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'255'}' title='$post_txt{'255'}' border='0' \/>");
				document.write("<img src='$imagesdir/strike.gif' onclick='strike();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'441'}' title='$post_txt{'441'}' border='0' \/>");
				document.write("<img src='$imagesdir/highlight.gif' onclick='highlight();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'246'}' title='$post_txt{'246'}' border='0' />");
				document.write('</div>');
				document.write('<div style="width: 139px; float: left; text-align: center;">');
				document.write('<select name="fontface" id="fontface" onchange="if(this.options[this.selectedIndex].value) fontfce(this.options[this.selectedIndex].value);" style="width: 90px; margin-top: 2px; margin-left: 2px; margin-right: 1px; font-size: 9px;">');
				document.write('<option value="">Verdana<\/option>');
				document.write('<option value="">\\-\\-\\-\\-\\-<\/option>');
				document.write('<option value="Sans-Serif" style="font-family: Sans-Serif">Sans-Serif</option>');
				document.write('<option value="Verdana" style="font-family: Verdana" selected="selected">Verdana<\/option>');
				document.write('<option value="Arial" style="font-family: Arial">Arial<\/option>');
				document.write('<option value="Serif" style="font-family: Serif">Serif<\/option>');
				document.write('<option value="Courier" style="font-family: Courier">Courier<\/option>');
				document.write('<option value="Courier New" style="font-family: Courier New">Courier New<\/option>');
				document.write('<option value="monospace" style="font-family: monospace">Monospace<\/option>');
				document.write('</select>');
				document.write('<select name="fontsize" id="fontsize" onchange="if(this.options[this.selectedIndex].value) fntsize(this.options[this.selectedIndex].value);" style="width: 39px; margin-top: 2px; margin-left: 1px; margin-right: 2px; font-size: 9px;">');
				document.write('<option value="">11<\/option>');
				document.write('<option value="">\\-\\-<\/option>');
				document.write('<option value="6">6<\/option>');
				document.write('<option value="7">7<\/option>');
				document.write('<option value="8">8<\/option>');
				document.write('<option value="9">9<\/option>');
				document.write('<option value="10">10<\/option>');
				document.write('<option value="11" selected="selected">11<\/option>');
				document.write('<option value="12">12<\/option>');
				document.write('<option value="14">14<\/option>');
				document.write('<option value="16">16<\/option>');
				document.write('<option value="18">18<\/option>');
				document.write('<option value="20">20<\/option>');
				document.write('<option value="22">22<\/option>');
				document.write('<option value="24">24<\/option>');
				document.write('<option value="36">36<\/option>');
				document.write('<option value="48">48<\/option>');
				document.write('<option value="56">56<\/option>');
				document.write('<option value="72">72</option>');
				document.write('</select>');
				document.write('</div>');
			}
			//-->
			</script>
			$ubbcpalette
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "WebTV Plus Receiver" && navigator.appVersion.charAt(0) >= 3) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer; cursor: hand;'";
				document.write('<div style="width: 92px; float: left;">');
				document.write("<img src='$imagesdir/pre.gif' onclick='pre();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'444'}' title='$post_txt{'444'}' border='0' />");
				document.write("<img src='$imagesdir/left.gif' onclick='left();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'445'}' title='$post_txt{'445'}' border='0' />");
				document.write("<img src='$imagesdir/center.gif' onclick='center();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'256'}' title='$post_txt{'256'}' border='0' />");
				document.write("<img src='$imagesdir/right.gif' onclick='right();' "+HAND+" align='top' width='23' height='22' alt='$post_txt{'446'}' title='$post_txt{'446'}' border='0' />");
				document.write('</div>');
			}
			else { document.write("<span class='small'>$post_txt{'215'}</span>"); }
			//-->
			</script>
			<noscript>
			<span class="small">$post_txt{'215'}</span>
			</noscript>
			</div>
			~;
		}
	}
	
	if ($replyguest) {
		$tmpmtext =qq~<b>$post_txt{'72'}:</b> ~;
	}

	$imsend .= qq~
		<div style="float: left; width: 99%;">
		$tmpmtext<textarea name="message" id="message" rows="8" cols="68" style="height: 200px; width: 95%; font-family: Verdana; font-size: 11px; padding: 5px; margin: 0px; visibility: visible;" onclick="javascript:storeCaret(this);" onkeyup="javascript:storeCaret(this);" onchange="javascript:storeCaret(this);" tabindex="4">$message</textarea>
		</div>
		</td>
	</tr>
	~;

	if (!$replyguest) {
		$imsend .= qq~
	<tr>
		<td valign="middle" class="windowbg2">
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			if((navigator.appName == "Netscape" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Opera" && navigator.appVersion.charAt(0) >= 4) || (navigator.appName == "Konqueror" && navigator.appVersion.charAt(0) >= 2)) {
				HAND = "style='cursor: pointer; cursor: hand;'";
				document.write("<img src='$imagesdir/smiley.gif' onclick='smiley();' "+HAND+" align='bottom' alt='$post_txt{'287'}' title='$post_txt{'287'}' border='0'> ");
				document.write("<img src='$imagesdir/wink.gif' onclick='wink();' "+HAND+" align='bottom' alt='$post_txt{'292'}' title='$post_txt{'292'}' border='0'> ");
				document.write("<img src='$imagesdir/cheesy.gif' onclick='cheesy();' "+HAND+" align='bottom' alt='$post_txt{'289'}' title='$post_txt{'289'}' border='0'> ");
				document.write("<img src='$imagesdir/grin.gif' onclick='grin();' "+HAND+" align='bottom' alt='$post_txt{'293'}' title='$post_txt{'293'}' border='0'> ");
				document.write("<img src='$imagesdir/angry.gif' onclick='angry();' "+HAND+" align='bottom' alt='$post_txt{'288'}' title='$post_txt{'288'}' border='0'> ");
				document.write("<img src='$imagesdir/sad.gif' onclick='sad();' "+HAND+" align='bottom' alt='$post_txt{'291'}' title='$post_txt{'291'}' border='0'> ");
				document.write("<img src='$imagesdir/shocked.gif' onclick='shocked();' "+HAND+" align='bottom' alt='$post_txt{'294'}' title='$post_txt{'294'}' border='0'> ");
				document.write("<img src='$imagesdir/cool.gif' onclick='cool();' "+HAND+" align='bottom' alt='$post_txt{'295'}' title='$post_txt{'295'}' border='0'> ");
				document.write("<img src='$imagesdir/huh.gif' onclick='huh();' "+HAND+" align='bottom' alt='$post_txt{'296'}' title='$post_txt{'296'}' border='0'> ");
				document.write("<img src='$imagesdir/rolleyes.gif' onclick='rolleyes();' "+HAND+" align='bottom' alt='$post_txt{'450'}' title='$post_txt{'450'}' border='0'> ");
				document.write("<img src='$imagesdir/tongue.gif' onclick='tongue();' "+HAND+" align='bottom' alt='$post_txt{'451'}' title='$post_txt{'451'}' border='0'> ");
				document.write("<img src='$imagesdir/embarassed.gif' onclick='embarassed();' "+HAND+" align='bottom' alt='$post_txt{'526'}' title='$post_txt{'526'}' border='0'> ");
				document.write("<img src='$imagesdir/lipsrsealed.gif' onclick='lipsrsealed();' "+HAND+" align='bottom' alt='$post_txt{'527'}' title='$post_txt{'527'}' border='0'> ");
				document.write("<img src='$imagesdir/undecided.gif' onclick='undecided();' "+HAND+" align='bottom' alt='$post_txt{'528'}' title='$post_txt{'528'}' border='0'> ");
				document.write("<img src='$imagesdir/kiss.gif' onclick='kiss();' "+HAND+" align='bottom' alt='$post_txt{'529'}' title='$post_txt{'529'}' border='0'> ");
				document.write("<img src='$imagesdir/cry.gif' onclick='cry();' "+HAND+" align='bottom' alt='$post_txt{'530'}' title='$post_txt{'530'}' border='0'> ");$moresmilieslist
			} 
			else { document.write("<span  class='small'>$post_txt{'215'}</span>"); }
			//-->
			</script>
			~;

			if (($showadded == 3 && $showsmdir ne 2) || ($showsmdir eq 3 && $showadded ne 2)) {
				$imsend .= qq~
				<a href="javascript: smiliewin();">$post_smiltxt{'1'}</a>
				~;
			}

			$imsend .= qq~
			<noscript>
				<span class="small">$post_txt{'215'}</span>
			</noscript>
		</td>
	</tr>
	~;
	}

	$imsend .= qq~	
	<tr>
		<td class="windowbg2">
			<img src="$imagesdir/green1.gif" name="chrwarn" height="8" width="8" border="0" vspace="0" hspace="0" alt="" align="middle" />
			<span class="small">$npf_txt{'03'} <input value="$MaxMessLen" size="3" name="msgCL" class="windowbg2" style="border: 0px; font-size: 11px; width: 40px; padding: 1px" readonly="readonly" /></span>
	~;

	if ($INFO{'reply'}) {	# if this is a reply, need to pass the reply # forward 
		$imsend .= qq~<input type="hidden" name="replyno" id="replyno" value="%INFO{'reply'}" />~;
	}

	$imsend .= qq~
		</td>
	</tr>
	<tr>
		<td class="windowbg">
	~;
	
	if (!$replyguest) {
		$imsend .= qq~
			<input type="checkbox" name="ns" value="NS"$nscheck /> <span class="small"> $post_txt{'277'}</span><br />
		~;
		if ($FORM{'draft'} || $INFO{'caller'} == 4) {
			$imsend .= qq~
			<input type="checkbox" name="draftleave" id="draftleave" value="1" /> <span class="small"> $post_txt{'draftleave'}</span><br />
			~;
		}
	}

	$imsend .= qq~
		<div name="enable_iecopy" id="enable_iecopy" style="display: none;">
		<input type="checkbox" name="iecopy" id="iecopy"$iecopycheck /> <span class="small"> $post_txt{'iecopycheck'}</span>
		</div>
		<script language="JavaScript1.2" type="text/javascript">
		<!--
		if (navigator.appName == "Microsoft Internet Explorer") {
			document.getElementById('enable_iecopy').style.display = 'inline';
		}
		//-->
		</script>
		</td>
	</tr>
	~;
	
	#these are the buttons to submit
	my $sendBMessFlag;
	if ($sendBMess || $isBMess) {
		$sendBMessFlag = qq~<input type="hidden" name="isBMess" id="isBMess" value="yes" />~;
	}

	$imsend .= qq~
	<tr>
		<td align="center" class="titlebg" colspan="2">
		$hidestatus
		<span class="small">$post_txt{'329'}</span><br />
		$sendBMessFlag
		<input type="submit" name="$post" value="$submittxt" accesskey="s" tabindex="5" class="button" />
	~;

	if ($speedpostdetection) {
		$imsend .= qq~
			<script language="JavaScript1.2" type="text/javascript">
			<!--
			var postdelay = $min_post_speed*1000;
			document.postmodify.$post.value='$post_txt{"delay"}';
			document.postmodify.$post.disabled=true;
			document.postmodify.$post.style.cursor='default';
		  	var delay = window.setInterval('releasepost()',postdelay);
			function releasepost() {
				document.postmodify.$post.value='$submittxt';
				document.postmodify.$post.disabled=false;
				document.postmodify.$post.style.cursor='pointer';
				window.clearInterval(delay);
			}
			//-->
			</script>
			~;
	}

	if (!$replyguest) {
		if ((!$enable_PMcontrols && $enable_PMprev) || ($enable_PMcontrols && ${$uid.$username}{'pmmessprev'}))	{
			$imsend .= qq~
			<input type="submit" name="$preview" id="$preview" value="$inmes_txt{'507'}" accesskey="p" tabindex="6" class="button" />
			~;
		}
		$imsend .= qq~
			<input type="submit" name="$draft" id="$draft" value="$inmes_txt{'savedraft'}" accesskey="d" tabindex="7" class="button" />
		~;
	}

	unless ($is_preview) {
		$imsend .= qq~
		<input type="reset" value="$inmes_txt{'278'}" accesskey="r" tabindex="8" class="button" />~;
	}

	$imsend .= qq~
	        </td>
	      </tr>
	</form>
<script type="text/javascript" language="JavaScript">
<!--
	var noalert = true, gralert = false, rdalert = false, clalert = false;
	var prevsec = 5;
	var prevtxt;
	var cntsec = 0;
	function tick() {
		cntsec++;
		calcCharLeft();
		timerID = setTimeout("tick()",1000);
	}
	var autoprev = false;
	var topicfirst = true;
	~;

	if (((!$enable_PMcontrols && $enable_PMActprev) || ${$uid.$username}{'pmactprev'} eq 'on') && !$replyguest) {
		$imsend .= qq~	
		post_txt_807 = "$post_txt{'807'}";
		function enabPrev() {
			if ( autoprev == false ) {
				autoprev = true;
				topicfirst = true;
				document.getElementById("saveframe").style.visibility = "visible";
				document.getElementById("saveframe").style.height = "180px";
				document.getElementById("saveframe").style.width = "100%";
				document.getElementById("savetopic").style.visibility = "visible";
				document.getElementById("savetopic").style.height = "25px";
				document.getElementById("savetopic").style.width = "100%";
				document.getElementById("SaveInfo").style.visibility = "visible";
				document.getElementById("SaveInfo").style.height = "16px";
				document.getElementById("SaveInfo").style.width = "100%";
				document.postmodify.message.focus();
				document.images.prevwin.alt = "$npf_txt{'02'}";
				document.images.prevwin.title = "$npf_txt{'02'}";
				document.images.prevwin.src="$defaultimagesdir/cat_collapse.gif";
				autoPreview();
			} else {
				autoprev = false;
				ubbstr = '';
				document.getElementById("saveframe").style.visibility = "hidden";
				document.getElementById("saveframe").style.height = "0px";
				document.getElementById("savetopic").style.visibility = "hidden";
				document.getElementById("savetopic").style.height = "0px";
				document.getElementById("SaveInfo").style.visibility = "visible";
				document.getElementById("SaveInfo").style.height = "16px";
				document.postmodify.message.focus();
				document.images.prevwin.alt = "$npf_txt{'01'}";
				document.images.prevwin.title = "$npf_txt{'01'}";
				document.images.prevwin.src="$defaultimagesdir/cat_expand.gif";
			}
			calcCharLeft();
		}
	~;	
	}

	$imsend .= qq~		
		function calcCharLeft() {
			clipped = false;
			maxLength = $MaxMessLen;
			if (document.postmodify.message.value.length > maxLength) {
				document.postmodify.message.value = document.postmodify.message.value.substring(0,maxLength);
				charleft = 0;
				clipped = true;
			} else {
				charleft = maxLength - document.postmodify.message.value.length;
			}
			prevsec++
			if(autoprev && prevsec > 5 && prevtxt != document.postmodify.message.value) {
				autoPreview();
				prevtxt = document.postmodify.message.value;
			}
			document.postmodify.msgCL.value = charleft;
			if (charleft >= 100 && noalert) { noalert = false; gralert = true; rdalert = true; clalert = true; document.images.chrwarn.src="$defaultimagesdir/green1.gif"; }
			if (charleft < 100 && charleft >= 50 && gralert) { noalert = true; gralert = false; rdalert = true; clalert = true; document.images.chrwarn.src="$defaultimagesdir/green0.gif"; }
			if (charleft < 50 && charleft > 0 && rdalert) { noalert = true; gralert = true; rdalert = false; clalert = true; document.images.chrwarn.src="$defaultimagesdir/red0.gif" }
			if (charleft == 0 && clalert) { noalert = true; gralert = true; rdalert = true; clalert = false; document.images.chrwarn.src="$defaultimagesdir/red1.gif"; }
			return clipped;
		}

		var codestr = '$simpelcode';
		var quotstr = '$normalquot';
		var squotstr = '$simpelquot';
		var fontsizemax = '$fontsizemax';
		var fontsizemin = '$fontsizemin';
		var edittxt = '$edittext';
		var dispname = '$displayname';
		var scrpurl = '$scripturl';
		var imgdir = '$defaultimagesdir';
		var ubsmilieurl = '$smiliesurl';
		var parseflash = '$parseflash';
		var autolinkurl = '$autolinkurls';
		var Month = new Array($jsmonths);
		var timeselected = '$jstimeselected';
		var splittext = "$maintxt{'107'}";
		var dontusetoday = '$dontusetoday';
		var todaytext = "$maintxt{'769'}";
		var yesterdaytext = "$maintxt{'769a'}";
		var timetext1 = "$timetxt{'1'}";
		var timetext2 = "$timetxt{'2'}";
		var timetext3 = "$timetxt{'3'}";
		var timetext4 = "$timetxt{'4'}";

		function autoPreview() {
			if (topicfirst)  { updatTopic(); }
			var scrlto = parseInt(180) + 5;
			vismessage = document.postmodify.message.value;
			while ( c=vismessage.match(/date=(\\d+?)\\]/i) ) {
				var qudate=c[1];
				qudate=qudate * 1000;
				qdate=new Date();
				qdate.setTime(qudate);
				qdate=qdate.toLocaleString();
				vismessage=vismessage.replace(/(date=)\\d+?(\\])/i, "\$1"+qdate+"\$2");
			}
			if($enable_ubbc) {
				var ubbstr = jsDoUbbc(vismessage,codestr,quotstr,squotstr,edittxt,dispname,scrpurl,imgdir,ubsmilieurl,parseflash,fontsizemax,fontsizemin,autolinkurl,Month,timeselected,splittext,dontusetoday,todaytext,yesterdaytext,timetext1,timetext2,timetext3,timetext4);
			}
			else {
				var ubbstr = vismessage;
			}
			document.getElementById("saveframe").innerHTML=ubbstr;
			scrlto += parseInt(document.getElementById("saveframe").scrollTop) + parseInt(document.getElementById("saveframe").offsetHeight);
			document.getElementById("saveframe").scrollTop = scrlto;
			prevsec = 0;
		}
	~;

	if (((!$enable_PMcontrols && $enable_PMActprev) || ${$uid.$username}{'pmactprev'} eq 'on') && !$replyguest) {
		$imsend .= qq~
		var visikon = '';
		function updatTopic() {
			topicfirst = false;
			vistopic = document.postmodify.subject.value;
			var htmltopic = jsDoTohtml(vistopic);
			document.getElementById("savetopic").innerHTML=visikon+htmltopic;
			document.postmodify.message.focus();
		 }
	~;
	}

	$imsend .= qq~
		tick();
	~;	

	if (!$replyguest) {
		$imsend .= qq~
		function showtpstatus() {
			var theimg = '$pmicon';
			var objIconSelected = document.postmodify.status[document.postmodify.status.selectedIndex].value;
			if (objIconSelected == 's') { theimg = 'standard'; }
			if (objIconSelected == 'c') { theimg = 'confidential'; }
			if (objIconSelected == 'u') { theimg = 'urgent'; }
			document.images.icons.src='$imagesdir/'+theimg+'.gif';
		}
		document.onload = showtpstatus();
		~;
	}

	$imsend .= qq~
		// -->
		</script>	
	~;

		if ($action eq 'modify' || $action eq 'modify2') {
			$displayname = $mename;
		} else {
			$displayname = ${$uid.$username}{'realname'};
		}

		require "$templatesdir/$usedisplay/Display.template";

		foreach (@months) { $jsmonths .= qq~'$_',~; }
		$jsmonths =~ s~\,\Z~~;
		$jstimeselected = ${$uid.$username}{'timeselect'} || $timeselected;

		##########  end post code
}

##  process and send the IM to whomever
sub IMsendMessage {
	&LoadLanguage('Post');
	&LoadLanguage('InstantMessage');	
	##  load error strings
	&LoadLanguage('Error');
	##  sorry - no guests
	if ($iamguest) { &fatal_error("im_members_only"); }
	my (@ignore, $igname, $messageid, $subject, $message, @recipient, $ignored,$memnums);
	## grab subject
	$subject = $FORM{'subject'};
	$subject =~ s/\A\s+//;
	$subject =~ s/\s+\Z//;
	$isBMess = $FORM{'isBMess'};
	$tstsubject = $subject;
	#if (!$subject && !$FORM{'draft'}) { $subject = "$inmes_txt{'767'}"; }
	$message = $FORM{'message'};

	#  receipts for IM are now handled by "toshow" only, so we need to switch to the right 
	# test for no recipient. also switch on flag to stop us going back to the form all the time
	my $immulti;
	# if there is only the one (intended) recipient, 'to' must contain the name
	if ((!$FORM{'toshow'} && !$INFO{'to'}) && !$FORM{'draft'})	 { $error = $error_txt{'no_recipient'}; }
	my $toshow = $FORM{'toshow'};
	if (!$toshow) { $toshow = $INFO{'to'}; }
	# if there are several intended - can be one of course ;)
	# and of course, no subject/no message are bad!
	$error = $error_txt{'no_subject'}  unless ($subject);
	$error = $error_txt{'no_message'}  unless ($message);

	# Check Message Length Precisely
	$mess_len = $message;
	$mess_len =~ s/[\r\n ]//ig;
	$mess_len =~ s/&#\d{3,}?\;/X/ig;
	if (length($mess_len) > $MaxMessLen) { 
		$error = $inmes_txt{'536'} . " " . (length($mess_len) - $MaxMessLen) . " " . $inmes_txt{'537'};
	}
	undef $mess_len;

	# convert any &# to just # etc
	&FromChars($message);
	# force any amps to just the &
	$subject =~ s/&amp;/&/g;
	# same again for subject
	&FromChars($subject);
	$convertstr = $subject;
	$convertcut = 50;
	&CountChars;
	$subject = $convertstr;
	# remove any line returns
	$subject =~ s/[\r\n]//g;

	$mmessage = $message;
	$msubject = $subject;

	## censor message & subject
	&LoadCensorList;
	$mmessage = &Censor($mmessage);
	$msubject = &Censor($msubject);

	## convert back to html
	&ToHTML($message);

	## tabs to 3 x spaces
	$message =~ s/\t/ \&nbsp; \&nbsp; \&nbsp;/g;

	$message =~ s/\cM//g;
	$message =~ s/\n/<br \/>/g;

	if ($FORM{'ns'} eq 'NS') { $message .= "#nosmileys"; }

	if ($error) {
		$IM_box = $inmes_txt{'148'};
		$FORM{'previewim'} = 1;
		&IMPost;
		&buildIMsend;
		return;
	}

	undef @multiple;
	fopen(MEMLIST, "$memberdir/memberlist.txt");
	@memlist = <MEMLIST>;
	$allmems = @memlist;
	fclose(MEMLIST);
	&ProcIMrecs;

	$memnums   = $#multiple + 1;
	## no need to check for spam if its a broadcast, as this only creates the one post
	if ($imspam ne "off" && !$isBMess) {
		$checkspam = 100 / $allmems * $memnums;
		if ($memnums == 1) { $checkspam = 0; }
		if ($checkspam > $imspam && !$iamadmin) { &fatal_error("im_spam_alert"); }
	}
	$actlang = $language;
	my $UserTo;
	# go through each member in list
	# add to each msg (inbox) but only one to outbox
	# Create unique Message ID
	$messageid = &getnewid;
	if (!$FORM{'draft'} && !$error && !$isBMess && !$replyguest) {
		foreach $UserTo (@allto) {
			$addnr++;
			chomp $UserTo;
			my($status, $UserTo) = split(/:/, $UserTo);
			my $ignored = 0;
			$UserTo =~ s/\A\s+//;
			$UserTo =~ s/\s+\Z//;
			$UserTo =~ s/[^0-9A-Za-z#%+,-\.@^_]//g;

			# Check Ignore-List, unless sender is FA
			&LoadUser($UserTo);
			if (!$isBMess) {
				if (${$uid.$UserTo}{'im_ignorelist'} && $username ne 'admin') {
					# Build Ignore-List
					${$uid.$UserTo}{'im_ignorelist'} =~ s/[\n\r]//g;
					${$uid.$UserTo}{'im_notify'} =~ s/[\n\r]//g;
					@ignore = split(/\|/, ${$uid.$UserTo}{'im_ignorelist'});

					# If User is on Recipient's Ignore-List, show Error Message
					foreach $igname (@ignore) {
						# adds ignored user's name to array which error list will be built from later
						chomp $igname;
						if ($igname eq $username) { push(@nouser, $UserTo); $ignored = 1; }
						if ($igname eq '*') { push(@nouser, "$inmes_txt{'761'} $UserTo $inmes_txt{'762'};"); $ignored = 1; }
					}
				}
			}
			## check and see if 1) username is marked 'away' 2) they left a message 3) you haven't already had an auto-reply
			my $sendAutoReply = 'yes';
			if (${$uid.$UserTo}{'offlinestatus'} eq 'away' && ${$uid.$UserTo}{'awayreply'} ne '' && ${$uid.$UserTo}{'awaysubj'} ne '') {
				if (${$uid.$UserTo}{'awayreplysent'} eq '') {
					$sendAutoReply = 'yes';
					${$uid.$UserTo}{'awayreplysent'} = $username;}
				else {
					my @replyList = split(/,/ ,${$uid.$UserTo}{'awayreplysent'} );
					chomp @replyList;
					foreach my $replyListName (@replyList)	{
						$replyListName =~ s/^ //;
						if($replyListName eq $username)	{
							$sendAutoReply = 'no';
							last;
						}
					}
					if ($sendAutoReply eq 'yes') {
						if (${$uid.$UserTo}{'awayreplysent'} eq '') {${$uid.$UserTo}{'awayreplysent'} .= qq~$username~;}
						else { ${$uid.$UserTo}{'awayreplysent'} .= qq~,$username~; }
						&UserAccount($UserTo, 'update');
					}	
				}
			}
			else { $sendAutoReply = 'no'; }
			if (!-e ("$memberdir/$UserTo.vars")) { 
				# adds invalid user's name to array which error list will be built from later
				push(@nouser, $UserTo);
				$ignored = 1;
			}

			if (!$ignored) {
				# Send message to user
				fopen(INBOX, "$memberdir/$UserTo.msg");
				@inmessages = <INBOX>;
				fclose(INBOX);
				fopen(INBOX, ">$memberdir/$UserTo.msg");
				if ($status eq "to" || $status eq "cc") {
					print INBOX "$messageid|$username|$FORM{'toshow'}|$FORM{'toshowcc'}|$FORM{'toshowbcc'}|$subject|$date|$message|$messageid|0|$ENV{'REMOTE_ADDR'}|$FORM{'status'}|u||\n";
				} else {
					print INBOX "$messageid|$username|$FORM{'toshow'}|$FORM{'toshowcc'}|$FORM{'toshowbcc'}|$subject|$date|$message|$messageid|0|$ENV{'REMOTE_ADDR'}|$FORM{'status'}|u||\n";	
				}
				print INBOX @inmessages;
				fclose(INBOX);

				# we've added the msg to the inbox, now update the ims file
				&updateIMS($UserTo, $messageid, 'messagein');
				## if we need to drop the 'away' reply in....
				if ($sendAutoReply eq 'yes') {
					my $rmessageid = &getnewid;
					fopen(INBOX, "$memberdir/$username.msg");
					@myinmessages = <INBOX>;
					fclose(INBOX);
					fopen(INBOX, ">$memberdir/$username.msg");
					print INBOX "$rmessageid|$UserTo|$username|||${$uid.$UserTo}{'awaysubj'}|$date|${$uid.$UserTo}{'awayreply'}|$messageid|1|$ENV{'REMOTE_ADDR'}|s|ur||\n";
					fclose(INBOX);
				}
				## relocated sender's msg out of the loop

				# Send notification (Will only work if Admin has allowed the Email Notification)
				if (${$uid.$UserTo}{'im_notify'} == 1 && $enable_notification == 1) {
					require "$sourcedir/Mailer.pl";
					$language = ${$uid.$UserTo}{'language'};
					&LoadLanguage('Email');
					&LoadLanguage('Notify');
					$mydate = &timeformat($date);
					$useremail = ${$uid.$UserTo}{'email'};
					$useremail =~ s/[\n\r]//g;    # get email address
					if ($useremail ne '') {
						if (!$tstsubject) { $msubject = $inmes_txt{'767'}; }
						$fromname = ${$uid.$username}{'realname'};
						&ToChars($msubject);
						$chmessage = $mmessage;
						&ToChars($chmessage);
						$chmessage =~ s~\[b\](.*?)\[/b\]~*$1*~isg;
						$chmessage =~ s~\[i\](.*?)\[/i\]~/$1/~isg;
						$chmessage =~ s~\[u\](.*?)\[/u\]~_$1_~isg;
						$chmessage =~ s~\[.*?\]~~g;
						my $message = &template_email($privatemessagenotificationemail, {'date' => $mydate, 'subject' => $msubject, 'sender' => $fromname, 'message' => $chmessage});
						&sendmail($useremail, $notify_txt{'145'}, $message, '', $emailcharset);
					}
				}
			}	#end add PM to outbox
		}    #end foreach loop
		if ($#allto == $#nouser) {
			my $badusers;
			foreach my $baduser (@nouser) {
				&LoadUser($baduser);
				$badusers .= qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$baduser}">${$uid.$baduser}{'realname'}</a>, ~;
			}
			$badusers =~ s/, \Z//;
			&fatal_error('im_bad_users', $badusers);
		}
	}

	##  moved sender's reply marker here, open the sender's inbox and mark 'replied'
	if (!$error) {
		if ($isBMess) {
			fopen(INBOX, "$memberdir/broadcast.messages");
			@inmessages = <INBOX>;
			fclose(INBOX);
			fopen(INBOX, ">$memberdir/broadcast.messages");
			$FORM{'toshow'} =~ s/bmallmembers/all/;
			$FORM{'toshow'} =~ s/bmgmods/gmods/;
			$FORM{'toshow'} =~ s/bmmods/mods/;
			print INBOX "$messageid|$username|$FORM{'toshow'}|||$subject|$date|$message|$messageid|0|$ENV{'REMOTE_ADDR'}|$FORM{'status'}b|u||\n";
			print INBOX @inmessages;
			fclose(INBOX);	
		}

		if ($INFO{'reply'}) {
			my $id = $INFO{'id'};
			## mark msg replied
			&updateIMS($username, $id, 'reply');
		}

		## this now outside the foreach, to allow just one write in the outbox
		# Add message to outbox, read outbox

		@outmessages = ();
		my $savetofile = 'outbox';
		if ($FORM{'draft'}) { $savetofile = 'imdraft'; }
		fopen(OUTBOX, "$memberdir/$username.$savetofile");
		@outmessages = <OUTBOX>;
		fclose(OUTBOX);

		# add the PM to the outbox
		# the sep users now live together
		my $usersString = join(',',@multiple);
		my $messFlag = '';
		if ($isBMess) { $messFlag = 'b'; }
		if ($replyguest) { 
			$messFlag = 'gr';

			$FORM{'toguest'} =~ s/ /%20/g;
			$FORM{'toshow'} = $FORM{'toguest'} . ' ' . $FORM{'guestemail'};
			$FORM{'toshow'} =~ s/[\n\r]//g;
			$FORM{'guestemail'} =~ s/[\n\r]//g;

			$fromname = ${$uid.$username}{'realname'};

			&ToChars($msubject);

			$chmessage = $mmessage;
			&ToChars($chmessage);
			$chmessage =~ s~\[b\](.*?)\[/b\]~*$1*~isg;
			$chmessage =~ s~\[i\](.*?)\[/i\]~/$1/~isg;
			$chmessage =~ s~\[u\](.*?)\[/u\]~_$1_~isg;
			$chmessage =~ s~\[.*?\]~~g;
			$chmessage =~ s/\r(?=\n*)//g;

			require "$sourcedir/Mailer.pl";
			&sendmail($FORM{'guestemail'}, $msubject, $chmessage, ${$uid.$username}{'email'});
		}

		fopen(OUTBOX, "+>$memberdir/$username.$savetofile");
		## all but drafts being resaved just get added to their file
		if (!$FORM{'draft'} || ($FORM{'draft'} && !$FORM{'draftid'}) || ($FORM{'draft'} && ($FORM{'quote'} || $FORM{'reply'} || $FORM{'forward'}))) {
			print OUTBOX "$messageid|$username|$FORM{'toshow'}|$FORM{'toshowcc'}|$FORM{'toshowbcc'}|$subject|$date|$message|$messageid|$FORM{'replyno'}|$ENV{'REMOTE_ADDR'}|$FORM{'status'}$messFlag||\n";
			print OUTBOX @outmessages;
		}
		elsif ($FORM{'draft'} && $FORM{'draftid'}) {
			## resaving draft - find draft message id and amend the entry
			foreach my $outmessage (@outmessages) {
				chomp $outmessage;
				my $omid = (split /\|/, $outmessage)[0];
				if ($omid ne $FORM{'draftid'}) {
					print OUTBOX "$outmessage\n";
				} else {
					print OUTBOX "$messageid|$username|$FORM{'toshow'}|$FORM{'toshowcc'}|$FORM{'toshowbcc'}|$subject|$date|$message|$messageid|$FORM{'reply'}|$ENV{'REMOTE_ADDR'}|$FORM{'status'}$messFlag||\n";
				}
			}
		}
		fclose(OUTBOX);

		## pdate ims for sent
		if (!$FORM{'draft'}) { &updateIMS($username, $messageid, 'messageout'); }
		else { &updateIMS($username, $messageid, 'draftadd'); }

		## if this is a draft being sent, remove it from the draft file
		if ($FORM{'draftid'} && $FORM{'draft'} ne $inmes_txt{'savedraft'} && !$FORM{'draftleave'}) {
			fopen(DRAFTFILE, "$memberdir/$username.imdraft");
			my @draftPM = <DRAFTFILE>;
			fclose(DRAFTFILE);
			fopen(DRAFTFILE, ">$memberdir/$username.imdraft");
			seek DRAFTFILE,0,0;
			foreach my $draftmess (@draftPM) {
				chomp $draftmess;
				my $draftMID = (split /\|/, $draftmess)[0];
				if ($draftMID ne $FORM{'draftid'}) { print DRAFTFILE "$draftmess\n"; }
			}
			fclose(DRAFTFILE);
		}
		# invalid users 
		#if there were invalid usernames in the recipient list, these names are listed after all valid users have been IMed
		if (!$FORM{'draft'}) {
			if (@nouser) {
				my $badusers;
				foreach my $baduser (@nouser) {
					&LoadUser($baduser);
					$badusers .= qq~<a href="$scripturl?action=viewprofile;username=$useraccount{$baduser}">${$uid.$baduser}{'realname'}</a>, ~;
				}
				$badusers =~ s/, \Z//;
				&fatal_error('im_bad_users', $badusers);
			}
		}
		
		## saving a draft doesn't count as sending
		if (!$FORM{'draft'}) { &UserAccount($username, 'update', 'lastim'); }
		&UserAccount($username, 'update', 'lastonline');
		$PMmessageProcessed = $inmes_txt{'messagesent'};
	}
	if ($FORM{'draft'}) { $PMmessageProcessed = $inmes_txt{'savedtodraft'}; }
	if ($FORM{'draft'}) { $yySetLocation = qq~$scripturl?action=imdraft~; }
	else	{ $yySetLocation = qq~$scripturl?action=imoutbox~; }
	&redirectexit;
}


##  process the to/cc/bcc lists
sub ProcIMrecs {		

	$FORM{'toshow'} =~ s/ //g;

	if (!$isBMess) {
		my $countMulti = 0;
		@multiple = split(/\,/, $FORM{'toshow'});
		foreach my $multiUser (@multiple) {
			if ($do_scramble_id) { $multiple[$countMulti] = &decloak($multiUser); }
			$countMulti++ ;
		}
		$toshowList = join(',', @multiple);
		$toshowList = qq~to:$toshowList~;
		$toshowList =~ s/,/,to:/g; 
		push(@allto, split(/\,/,$toshowList));
		$FORM{'toshow'} = join(',', @multiple);
	
		$FORM{'toshowcc'} =~ s/ //g;
		$FORM{'toshowbcc'} =~ s/ //g;

		if ($FORM{'toshowcc'}) {
			my $countMulti = 0;
			@multiplecc = split(/\,/, $FORM{'toshowcc'});
			foreach my $multiUser (@multiplecc) {
				$multiUser =~ s/ //g;
				if ($do_scramble_id) { $multiplecc[$countMulti] = &decloak($multiUser); }
				else { $multiplecc[$countMulti] = $multiUser; }
				$countMulti++ ;
			}
			$toshowccList = join(',', @multiplecc);
			$toshowccList = qq~cc:$toshowccList~;
			$toshowccList =~ s/,/,cc:/g; 
			push(@allto, split(/\,/,$toshowccList));
			$FORM{'toshowcc'} = join(',', @multiplecc);
		}
		if ($FORM{'toshowbcc'}) {
			my $countMulti = 0;
			@multiplebcc = split(/\,/, $FORM{'toshowbcc'});
			foreach my $multiUser (@multiplebcc) {
				$multiUser =~ s/ //g;
				if ($do_scramble_id) { $multiplebcc[$countMulti] = &decloak($multiUser); }
				else{$multiplebcc[$countMulti] = $multiUser;}
				$countMulti++ ;
			}
			$toshowbccList = join(',', @multiplebcc);
			$toshowbccList = qq~bcc:$toshowbccList~;
			$toshowbccList =~ s/,/,bcc:/g;
			push(@allto, split(/\,/,$toshowbccList));
			$FORM{'toshowbcc'} = join(',', @multiplebcc);
		}
	}
}

sub pageLinksList {
	# Build the page links list.
	$maxmessagedisplay ||= 10;
	my $userthreadpage = (split /\|/, ${$uid.$username}{'pageindex'})[3];
	my ($pagetxtindex, $pagetextindex, $pagedropindex1, $pagedropindex2, $all, $allselected, $bmesslink);
	$postdisplaynum = 3; # max number of pages to display
	$dropdisplaynum = 10;
	$startpage = 0;
	if ($viewfolder ne '') { $viewfolderinfo = qq~;viewfolder=$viewfolder~; }
	if ($INFO{'focus'} eq 'bmess') { $bmesslink = qq~;focus=bmess~;}
	$max = $#dimmessages + 1;
	if ($INFO{'start'} eq "all") { $maxmessagedisplay = $max; $all = 1; $allselected = qq~ selected="selected"~; $start = 0; }
	else { $start = $INFO{'start'} || 0; }
	$start = $start > $#dimmessages ? $#dimmessages : $start;
	$start = (int($start / $maxmessagedisplay)) * $maxmessagedisplay;
	$tmpa = 1;
	$pagenumb = int(($max - 1) / $maxmessagedisplay) + 1;
	if ($start >= (($postdisplaynum - 1) * $maxmessagedisplay)) {
		$startpage = $start - (($postdisplaynum - 1) * $maxmessagedisplay);
		$tmpa = int($startpage / $maxmessagedisplay) + 1;
	}
	if ($max >= $start + ($postdisplaynum * $maxmessagedisplay)) { $endpage = $start + ($postdisplaynum * $maxmessagedisplay); }
	else { $endpage = $max; }
	$lastpn = int($#dimmessages / $maxmessagedisplay) + 1;
	$lastptn = ($lastpn - 1) * $maxmessagedisplay;
	$pageindex1 = qq~<span class="small" style="float: left; height: 21px; margin: 0px; margin-top: 2px;"><img src="$imagesdir/index_togl.gif" border="0" alt="" style="vertical-align: middle;" /> $display_txt{'139'}: $pagenumb</span>~;
	if ($pagenumb > 1 || $all) {
		if ($userthreadpage == 1 ) {
			$pagetxtindexst = qq~<span class="small" style="float: left; height: 21px; margin: 0px; margin-top: 2px;">~;
			$pagetxtindexst .= qq~<a href="$scripturl?pmaction=$action$bmesslink;start=$start;action=pmpagetext$viewfolderinfo"><img src="$imagesdir/index_togl.gif" border="0" alt="$display_txt{'19'}" style="vertical-align: middle;" /></a> $display_txt{'139'}: ~; 
			if ($startpage > 0) { $pagetxtindex = qq~<a href="$scripturl?action=$action$bmesslink/0$viewfolderinfo" style="font-weight: normal;">1</a>&nbsp;...&nbsp;~; }
			if ($startpage == $maxmessagedisplay) { $pagetxtindex = qq~<a href="$scripturl?action=$action$bmesslink;start=0$viewfolderinfo" style="font-weight: normal;">1</a>&nbsp;~; }
			for ($counter = $startpage; $counter < $endpage; $counter += $maxmessagedisplay) {
				$pagetxtindex .= $start == $counter ? qq~<b>$tmpa</b>&nbsp;~ : qq~<a href="$scripturl?action=$action$bmesslink;start=$counter$viewfolderinfo" style="font-weight: normal;">$tmpa</a>&nbsp;~;
				$tmpa++;
			}
			if ($endpage < $max - ($maxmessagedisplay)) { $pageindexadd = qq~...&nbsp;~; }
			if ($endpage != $max) { $pageindexadd .= qq~<a href="$scripturl?action=$action$bmesslink;start=$lastptn$viewfolderinfo" style="font-weight: normal;">$lastpn</a>~; }
			$pagetxtindex .= qq~$pageindexadd~;
			$pageindex1 = qq~$pagetxtindexst$pagetxtindex</span>~;
			$pageindex2 = $pageindex1;
		} else {
			$pagedropindex1 = qq~<span style="float: left; width: 320px; margin: 0px; margin-top: 2px; border: 0px;">~;
			$pagedropindex1 .= qq~<span style="float: left; height: 21px; margin: 0; margin-right: 4px;"><a href="$scripturl?pmaction=$action$bmesslink;start=$start;action=pmpagedrop$viewfolderinfo"><img src="$imagesdir/index_togl.gif" border="0" alt="$display_txt{'19'}" /></a></span>~;
			$pagedropindex2 = $pagedropindex1;
			$tstart = $start;
			if (substr($INFO{'start'}, 0, 3) eq "all") { ($tstart, $start) = split(/\-/, $INFO{'start'}); }
			$d_indexpages = $pagenumb / $dropdisplaynum;
			$i_indexpages = int($pagenumb / $dropdisplaynum);
			if ($d_indexpages > $i_indexpages) { $indexpages = int($pagenumb / $dropdisplaynum) + 1; }
			else { $indexpages = int($pagenumb / $dropdisplaynum) }
			$selectedindex = int(($start / $maxmessagedisplay) / $dropdisplaynum);
			if ($pagenumb > $dropdisplaynum) {
				$pagedropindex1 .= qq~<span style="float: left; height: 21px; margin: 0;"><select size="1" name="decselector1" id="decselector1" style="font-size: 9px; border: 2px inset;" onchange="if(this.options[this.selectedIndex].value) SelDec(this.options[this.selectedIndex].value, 'xx')">\n~;
				$pagedropindex2 .= qq~<span style="float: left; height: 21px; margin: 0;"><select size="1" name="decselector2" id="decselector2" style="font-size: 9px; border: 2px inset;" onchange="if(this.options[this.selectedIndex].value) SelDec(this.options[this.selectedIndex].value, 'xx')">\n~;
			}
			for ($i = 0; $i < $indexpages; $i++) {
				$indexpage = ($i * $dropdisplaynum) * $maxmessagedisplay;
				$indexstart = ($i * $dropdisplaynum) + 1;
				$indexend = $indexstart + ($dropdisplaynum - 1);
				if ($indexend > $pagenumb) { $indexend   = $pagenumb; }
				if ($indexstart == $indexend) { $indxoption = qq~$indexstart~; }
				else { $indxoption = qq~$indexstart-$indexend~; }
				$selected = "";
				if ($i == $selectedindex) {
					$selected    = qq~ selected="selected"~;
					$pagejsindex = qq~$indexstart|$indexend|$maxmessagedisplay|$indexpage~;
				}
				if ($pagenumb > $dropdisplaynum) {
					$pagedropindex1 .= qq~<option value="$indexstart|$indexend|$maxmessagedisplay|$indexpage"$selected>$indxoption</option>\n~;
					$pagedropindex2 .= qq~<option value="$indexstart|$indexend|$maxmessagedisplay|$indexpage"$selected>$indxoption</option>\n~;
				}
			}
			if ($pagenumb > $dropdisplaynum) {
				$pagedropindex1 .= qq~</select>\n</span>~;
				$pagedropindex2 .= qq~</select>\n</span>~;
			}
			$pagedropindex1 .= qq~<span id="ViewIndex1" class="droppageindex" style="height: 14px; visibility: hidden;">&nbsp;</span>~;
			$pagedropindex2 .= qq~<span id="ViewIndex2" class="droppageindex" style="height: 14px; visibility: hidden;">&nbsp;</span>~;
			$tmpmaxmessagedisplay = $maxmessagedisplay;
			if (substr($INFO{'start'}, 0, 3) eq "all") { $maxmessagedisplay = $maxmessagedisplay * $dropdisplaynum; }
			$prevpage = $start - $tmpmaxmessagedisplay;
			$nextpage = $start + $maxmessagedisplay;
			$pagedropindexpvbl = qq~<img src="$imagesdir/index_left0.gif" height="14" width="13" border="0" alt="" style="margin: 0px; display: inline; vertical-align: middle;" />~;
			$pagedropindexnxbl = qq~<img src="$imagesdir/index_right0.gif" height="14" width="13" border="0" alt="" style="margin: 0px; display: inline; vertical-align: middle;" />~;
			if ($start < $maxmessagedisplay) { $pagedropindexpv .= qq~<img src="$imagesdir/index_left0.gif" height="14" width="13" border="0" alt="" style="display: inline; vertical-align: middle;" />~; }
			else { $pagedropindexpv .= qq~<img src="$imagesdir/index_left.gif" border="0" height="14" width="13" alt="$pidtxt{'02'}" style="display: inline; vertical-align: middle; cursor: pointer;" onclick="location.href=\\'$scripturl?action=$action$bmesslink;start=$prevpage\\'" ondblclick="location.href=\\'$scripturl?action=$action$bmesslink;start=0\\'" />~; }
			if ($nextpage > $lastptn) { $pagedropindexnx .= qq~<img src="$imagesdir/index_right0.gif" border="0" height="14" width="13" alt="" style="display: inline; vertical-align: middle;" />~; }
			else { $pagedropindexnx .= qq~<img src="$imagesdir/index_right.gif" height="14" width="13" border="0" alt="$pidtxt{'03'}" style="display: inline; vertical-align: middle; cursor: pointer;" onclick="location.href=\\'$scripturl?action=$action$bmesslink;start=$nextpage\\'" ondblclick="location.href=\\'$scripturl?action=$action$bmesslink;start=$lastptn\\'" />~; }
			$pageindex1 = qq~$pagedropindex1</span>~;
			$pageindexjs = qq~
			<script language="JavaScript1.2" type="text/javascript">
			<!-- 
			function SelDec(decparam, visel) {
				splitparam = decparam.split("|");
				var vistart = parseInt(splitparam[0]);
				var viend = parseInt(splitparam[1]);
				var maxpag = parseInt(splitparam[2]);
				var pagstart = parseInt(splitparam[3]);
				var allpagstart = parseInt(splitparam[3]);
				if (visel == 'xx' && decparam == '$pagejsindex') visel = '$tstart';
				var pagedropindex = '<table border="0" cellpadding="0" cellspacing="0"><tr>';
				for (i=vistart; i<=viend; i++) {
					if (visel == pagstart) pagedropindex += '<td class="titlebg" height="14" style="height: 14px; padding-left: 1px; padding-right: 1px; font-size: 9px; font-weight: bold;">' + i + '</td>';
					else pagedropindex += '<td height="14" class="droppages"><a href="$scripturl?action=$action$bmesslink;start=' + pagstart + '">' + i + '</a></td>';
					pagstart += maxpag;
				}
				~;
				if ($showpageall) {
					$pageindexjs .= qq~
					if (vistart != viend) {
						if(visel == 'all') pagedropindex += '<td class="titlebg" height="14" style="height: 14px; padding-left: 1px; padding-right: 1px; font-size: 9px; font-weight: normal;"><b>$pidtxt{"01"}</b></td>';
						else pagedropindex += '<td height="14" class="droppages"><a href="$scripturl?action=$action$bmesslink;start=all-' + allpagstart + '">$pidtxt{"01"}</a></td>';
					}
					~;
				}
				$pageindexjs .= qq~
				if (visel != 'xx') pagedropindex += '<td height="14" class="small" style="height: 14px; padding-left: 4px;">$pagedropindexpv$pagedropindexnx</td>';
				else pagedropindex += '<td height="14" class="small" style="height: 14px; padding-left: 4px;">$pagedropindexpvbl$pagedropindexnxbl</td>';
				pagedropindex += '</tr></table>';
				document.getElementById('ViewIndex1').innerHTML=pagedropindex;
				document.getElementById('ViewIndex1').style.visibility = 'visible';
				~;
				if ($pagenumb > $dropdisplaynum) {
				$pageindexjs .= qq~
				document.getElementById('decselector1').value = decparam;
				~;
			}
			$pageindexjs .= qq~
		}
		document.onload = SelDec('$pagejsindex', '$tstart');
		//-->
		</script>
		~;
		}
	}
}

##  output one or all IM - detailed view
sub DoShowIM {
	$messfound = 0;
	if ($callerid < 5) { &updateIMS($username, $_[0], 'inread'); }
	else { &updateIMS($username, $_[0], 'bmread'); }
	my ($showIM, $fromTitle, $toTitle, $toTitleCC, $toTitleBCC, $usernamelinkfrom, $usernamelinkto, $usernamelinkcc, $usernamelinkbcc, $userOnline, $prevMessId, $nextMessid, $PMnav, $mccusersshow, $mbccusersshow);
	$messcount = 0;
	foreach my $messagesim (@dimmessages) {
		$nextMessid = $messageid;
		($messageid, $musername, $mtousers, $mccusers, $mbccusers, $msub, $mdate, $immessage, $mpmessageid, $mreplyno, $imip, $mstatus, $mflags, $mstorefolder, $mattach) = split(/\|/, $messagesim);
		$messcount++;
		if ($messageid == $_[0]) { $messfound = 1; last; }
	}
	## if not at the end of the list, catch the 'previoous' id
	if($messcount <= $#dimmessages){
		($prevMessId, undef) = split(/\|/, $dimmessages[$messcount]);
	}
	## wrap the URL in
	if ($INFO{'id'} ne 'all' && $prevMessId ne '') { $previd = qq~&laquo; <a href="$scripturl?action=imshow;caller=$INFO{'caller'};id=$prevMessId">$inmes_imtxt{'40'}</a>~; }
	if ($INFO{'id'} ne 'all' && $nextMessid ne '') { $nextid = qq~<a href="$scripturl?action=imshow;caller=$INFO{'caller'};id=$nextMessid">$inmes_imtxt{'41'}</a> &raquo;~; }
	if ($INFO{'id'} ne 'all' && $#dimmessages > 0) { $allid = qq~<a href="$scripturl?action=imshow;caller=$INFO{'caller'};id=all">$inmes_txt{'190'}</a>~; }	

	my $mydate = &timeformat($mdate);
	if ($INFO{'caller'} == 1) {
		if ($mtousers) {
			foreach my $uname (split(/\,/, $mtousers)) {
				&LoadValidUserDisplay($uname);
				$usernamelinkto .= &CreateUserDisplayLine($uname) . ', ';
			}
			$usernamelinkto =~ s/, \Z//;
			$toTitle = qq~$inmes_txt{'324'}:~;
		}
		if ($mccusers) {
			foreach my $uname (split(/\,/, $mccusers)) {
				if ($uname eq $username) {
					$mccusersshow = 1;
					&LoadValidUserDisplay($uname);
					$usernamelinkcc .= &CreateUserDisplayLine($uname) . ', ';
				}
			}
			if ($mccusersshow) {
				$usernamelinkcc =~ s/, \Z//;
				$toTitleCC = qq~$inmes_txt{'325'}:~;
			}
		}
		if ($mbccusers) {
			foreach my $uname (split(/\,/, $mbccusers)) {
				if ($uname eq $username) {
					$mbccusersshow = 1;
					&LoadValidUserDisplay($uname);
					$usernamelinkbcc .= &CreateUserDisplayLine($uname) . ', ';
				}
			}
			if ($mbccusersshow) {
				$usernamelinkbcc =~ s/, \Z//;
				$toTitleBCC = qq~$inmes_txt{'326'}:~;
			}
		}
		if ($musername ne '') {
			&LoadValidUserDisplay($musername);
			$usernamelinkfrom = &CreateUserDisplayLine($musername);
			$fromTitle = qq~$inmes_txt{'318'}:~;
		}
	}
	elsif ($INFO{'caller'} == 2) {
		if ($musername ne '') {
			&LoadValidUserDisplay($musername);
			$usernamelinkfrom = &CreateUserDisplayLine($musername);
			$fromTitle = qq~$inmes_txt{'318'}:~;
		}
		if ($mstatus !~ /b/) {
			if ($mstatus !~ /gr/) {
				foreach my $uname (split(/\,/, $mtousers)) {
					&LoadValidUserDisplay($uname);
					$usernamelinkto .= &CreateUserDisplayLine($uname) . ', ';
				}
			} else {
				my ($guestName, $guestEmail) = split(/\ /, $mtousers);
				$guestName =~ s/%20/ /g; 
				$usernamelinkto = qq~$guestName (<a href="mailto:$guestEmail">$guestEmail</a>)~;
			}
			$toTitle = qq~$inmes_txt{'324'}:~;
		} else {
			foreach my $uname (split(/\,/, $mtousers)) {
				if ($uname eq 'all') { $usernamelinkto .= qq~<b>$inmes_txt{'bmallmembers'}</b>~ . ', '; }
				elsif ($uname eq 'mods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmmods'}</b>~ . ', '; }
				elsif ($uname eq 'gmods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmgmods'}</b>~ . ', '; }
				else {
					my ($title, undef) = split(/\|/, $NoPost{$uname}, 2);
					$usernamelinkto .= qq~<b>$title</b>~ . ', ';
				}
			}
			$toTitle = qq~$inmes_txt{'324'} $inmes_txt{'327'}:~;
		}
		$usernamelinkto =~ s/, \Z//;
		if ($mccusers) {
			foreach my $uname (split(/\,/, $mccusers)) {
				&LoadValidUserDisplay($uname);
				$usernamelinkcc .= &CreateUserDisplayLine($uname) . ', ';
			}
			$usernamelinkcc =~ s/, \Z//;
			$toTitleCC = qq~$inmes_txt{'325'}:~;
		}
		if ($mbccusers) {
			foreach my $uname (split(/\,/, $mbccusers)) {
				&LoadValidUserDisplay($uname);
				$usernamelinkbcc .= &CreateUserDisplayLine($uname) . ', ';
			}
			$usernamelinkbcc =~ s/, \Z//;
			$toTitleBCC = qq~$inmes_txt{'326'}:~;
		}
	}
	elsif ($INFO{'caller'} == 3) {
		if ($mstatus !~ /b/) {
			if ($mstatus !~ /gr/) {
				foreach my $uname (split(/\,/, $mtousers)) {
					&LoadValidUserDisplay($uname);
					$usernamelinkto .= &CreateUserDisplayLine($uname) . ', ';
				}
			} else {
				my ($guestName, $guestEmail) = split(/\ /, $mtousers);
				$guestName =~ s/%20/ /g; 
				$usernamelinkto = qq~$guestName (<a href="mailto:$guestEmail">$guestEmail</a>)~;
			}
			$toTitle = qq~$inmes_txt{'324'}:~;
			if ($mccusers && $musername eq $username) {
				foreach my $uname (split(/\,/, $mccusers)) {
					&LoadValidUserDisplay($uname);
					$usernamelinkcc .= &CreateUserDisplayLine($uname) . ', ';
				}
				$usernamelinkcc =~ s/, \Z//;
				$toTitleCC = qq~$inmes_txt{'325'}:~;
			}
			if ($mbccusers && $musername eq $username) {
				foreach my $uname (split(/\,/, $mbccusers)) {
					&LoadValidUserDisplay($uname);
					$usernamelinkbcc .= &CreateUserDisplayLine($uname) . ', ';
				}
				$usernamelinkbcc =~ s/, \Z//;
				$toTitleBCC = qq~$inmes_txt{'326'}:~;
			}
		} else {
			foreach my $uname (split(/\,/, $mtousers)) {
				if ($uname eq 'all') { $usernamelinkto .= qq~<b>$inmes_txt{'bmallmembers'}</b>~ . ', '; }
				elsif ($uname eq 'mods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmmods'}</b>~ . ', '; }
				elsif ($uname eq 'gmods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmgmods'}</b>~ . ', '; }
				else {
					my ($title, undef) = split(/\|/, $NoPost{$uname}, 2);
					$usernamelinkto .= qq~<b>$title</b>~ . ', ';
				}
			}
			$usernamelinkto =~ s/, \Z//;
			$toTitle = qq~$inmes_txt{'324'} $inmes_txt{'327'}:~;
		}
		if ($musername ne '') {
			&LoadValidUserDisplay($musername);
			$usernamelinkfrom = &CreateUserDisplayLine($musername);
			$fromTitle = qq~$inmes_txt{'318'}:~;
		}
	}
	elsif ($INFO{'caller'} == 5 && $mstatus eq 'g') {
		my ($guestName, $guestEmail) = split(/\ /, $musername);
		$guestName =~ s/%20/ /g;
		$usernamelinkfrom = qq~$guestName (<a href="mailto:$guestEmail">$guestEmail</a>)~;
		$fromTitle = qq~$inmes_txt{'318'}:~;
	}
	elsif ($INFO{'caller'} == 5 && $mstatus =~ /b/) {
		if ($mtousers) {
			foreach my $uname (split(/\,/, $mtousers)) {
				if ($uname eq 'all') { $usernamelinkto .= qq~<b>$inmes_txt{'bmallmembers'}</b>~ . ', '; }
				elsif ($uname eq 'mods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmmods'}</b>~ . ', '; }
				elsif ($uname eq 'gmods') { $usernamelinkto .= qq~<b>$inmes_txt{'bmgmods'}</b>~ . ', '; }
				else {
					my ($title, undef) = split(/\|/, $NoPost{$uname}, 2);
					$usernamelinkto .= qq~<b>$title</b>~ . ', ';
				}
			}
			$usernamelinkto =~ s/, \Z//;
			$toTitle = qq~$inmes_txt{'324'} $inmes_txt{'327'}:~;
		}
		if ($musername ne '') {
			&LoadValidUserDisplay($musername);
			$usernamelinkfrom = &CreateUserDisplayLine($musername);
			$fromTitle = qq~$inmes_txt{'318'}:~;
		}
	}

	$PMnav = &buildPMNavigator;

	$immessage = &Censor($immessage);
	$msub = &Censor($msub);
	&ToChars($msub);
	$message = $immessage;
	&wrap;
	if ($enable_ubbc) {
		if (!$yyYaBBCloaded) { require "$sourcedir/YaBBC.pl"; }
		&DoUBBC;
	}
	&wrap2;
	&ToChars($message);
	$avstyle = '';

	$showIM = qq~
<table border="0" width="100%" cellspacing="1" cellpadding="1" class="bordercolor">
<tr>
	<td class="windowbg" align="left" valign="top" colspan="2">
		<div style="width: 99%; padding: 2px; margin: 2px;">
	~;
	
	if ($fromTitle) {
		$showIM .= qq~
		<span class="small" style="width: 99%;">
		<b>$fromTitle</b> $usernamelinkfrom
		</span><br />
		~;
	}
	
	if ($toTitle) {
		$showIM .= qq~
		<span class="small" style="width: 99%;">
		<b>$toTitle</b> $usernamelinkto
		</span><br />
		~;
	}

	if ($toTitleCC) {
		$showIM .= qq~
		<span class="small" style="width: 99%;">
		<b>$toTitleCC</b> $usernamelinkcc
		</span><br />
		~;
	}

	if ($toTitleBCC) {
		$showIM .= qq~
		<span class="small" style="width: 99%;">
		<b>$toTitleBCC</b> $usernamelinkbcc
		</span><br />
		~;
	}

	$showIM .= qq~
		</div>
	</td>
</tr>
<tr>
	<td class="windowbg2" align="left" valign="top" colspan="2">
		<div style="width: 99%; padding: 2px; margin: 2px;">
		<span class="small" style="width: 99%;">
		<b>$inmes_txt{'70'}: $msub</b><br />
		<b>$inmes_txt{'317'}:</b> $mydate
		</span>
		</div>
	</td>
</tr>
<tr>
	<td class="windowbg2" align="left" valign="top" colspan="2">
		<div style="width: 99%; padding: 2px; margin: 2px;">
		<span class="message" style="float: left; width: 99%; overflow: auto; padding-bottom: 10px; margin-bottom: 10px;">
	        $message
		</span>
		</div>
	</td>
</tr>
~;

	if ($signature) {
		$showIM .= qq~
<tr>
	<td class="windowbg2" align="right" colspan="2">
	<div style="float: left; width: 99%; padding-top: 2px; margin-top: 2px; text-align: left;">
		<span class="small">$signature</span>
	</div>
	</td>
</tr>
		~;
	}
	
	if ($iamadmin || $iamgmod && $gmod_access2{'ipban2'} eq 'on') { $imip = $imip; }
	else { $imip = $inmes_txt{'511'}; }

	my $postMenuTemp = $sendEmail . $sendPM . $membAdInfo . "&nbsp;"; 
	$postMenuTemp =~ s/\Q$menusep//i;

	$showIM .= qq~
<tr>
	<td class="windowbg" align="right" colspan="2">
	<div style="float: left; width: 99%; padding-top: 5px; margin-top: 2px; text-align: right;">
		<span class="small"><img src="$imagesdir/ip.gif" border="0" alt="" /> $imip</span>
	</div>
	</td>
</tr>
<tr>
	<td class="windowbg2" align="left" valign="middle" colspan="2">
	<div style="float: left; text-align: left; width: 55%; padding: 2px; margin: 2px;">
		<span class="small">$postMenuTemp</span>
	</div>
	<div style="float: right; text-align: right; width: 40%; padding: 2px; margin: 2px;">
	<span class="small">~;

	if ($INFO{'caller'} == 1 || ($INFO{'caller'} == 3 && $musername ne '') || ($INFO{'caller'} == 5 && $musername ne '')) { ## inbox / stored inbox can reply/quote
		if ($mstatus eq 'g') {
			$showIM .= qq~<a href="$scripturl?action=imsend;caller=$INFO{'caller'};quote=1;replyguest=1;id=$messageid">$img{'reply_ims'}</a>~;
		} else {
			$showIM .= qq~
			<a href="$scripturl?action=imsend;caller=$INFO{'caller'};quote=1;to=$useraccount{$musername};id=$messageid">$img{'quote'}</a>$menusep
			<a href="$scripturl?action=imsend;caller=$INFO{'caller'};reply=1;to=$useraccount{$musername};id=$messageid">$img{'reply_ims'}</a>$menusep
	    		~;
		}
	}

	if ($INFO{'caller'} != 5) {
		$showIM .= qq~
        <a href="$scripturl?action=imsend;caller=$INFO{'caller'};quote=1;forward=1;id=$messageid">$img{'forward'}</a>$menusep~;
	}

	if ($INFO{'caller'} != 5 || ($INFO{'caller'} == 5 && ($iamadmin || $username eq $musername))) {
		$showIM .= qq~
        <a href="$scripturl?action=imremove;caller=$INFO{'caller'};id=$messageid" onclick="return confirm('$inmes_txt{'770'}');">$img{'im_remove'}</a>
       	~;
      }

	$showIM .= qq~
	</span>
	</div>
	</td>
</tr>
<tr>
<td align="right" class="windowbg2">
	<div style="float: left; text-align: left; width: 30%; padding: 2px; margin: 2px;"><span class="small">$recall</span>	</div>
	<div style="float: right; text-align: right; width: 60%; padding: 2px; margin: 2px;"><span class="small">$PMnav</span></div>
</td>
</tr>
</table>
</div>
~;

	return $showIM;
}

## build the links for single PM display
sub buildPMNavigator {
	if ($previd ne '') { $PMnav = qq~$previd~; }
	if ($allid ne '' && $previd ne '') { $PMnav .= qq~ | $allid~; }
	elsif ($allid ne '') { $PMnav = qq~$allid~; }
	if ($nextid ne '' && $allid ne '') { $PMnav .= qq~ | $nextid~; }
	return $PMnav;	
}
	
1;
